package com.nbjtjc.safe.service.sys;

import cn.hutool.core.collection.CollectionUtil;
import com.nbjtjc.safe.bean.Constant;
import com.nbjtjc.safe.bean.TreeNode;
import com.nbjtjc.safe.mapper.sys.SysPermissionMapper;
import com.nbjtjc.safe.model.sys.SysPermission;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SysPermissionService {


    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    //    @Cacheable(value = "permissionList",key = "#userId")
    public List<SysPermission> findMenuList(int userId) {
        List<SysPermission> permissionList = new ArrayList<>();

//        if (ShiroUtils.getSubject().hasRole(Constant.ROLE_ADMIN)) {
        if (userId == 1) {
            permissionList = getMenu(0);
        } else {
            permissionList = getMenu(userId);
        }
        return permissionList;
    }


    public List<SysPermission> getUserPermission(int userId) {
        List<SysPermission> topMenu = new ArrayList<>();
        Map<Integer, List<SysPermission>> parentIdMap = new HashMap<>();
        List<SysPermission> sysPermissions = sysPermissionMapper.selectAllByOrderNum();
        List<Integer> validIds = sysPermissionMapper.findPerIdsByUser(userId);
        HashSet<Integer> validIdSet = new HashSet<>(validIds);
        sysPermissions.forEach(permission -> {
            if (!parentIdMap.containsKey(permission.getParentId())) {
                List<SysPermission> permissions = new ArrayList<>();
                parentIdMap.put(permission.getParentId(), permissions);
            }
            if (userId == Constant.SUPER_ADMIN) {
                parentIdMap.get(permission.getParentId()).add(permission);
            } else {
                if (validIdSet.contains(permission.getId())) {
                    if (parentIdMap.containsKey(permission.getParentId())) {
                        parentIdMap.get(permission.getParentId()).add(permission);
                    } else {
                        List<SysPermission> permissions = new ArrayList<>();
                        permissions.add(permission);
                        parentIdMap.put(permission.getParentId(), permissions);
                    }
                }
            }
        });
        if (userId == Constant.SUPER_ADMIN) {
            SysPermission sysPermission = new SysPermission();
            sysPermission.setType(0);
            topMenu = sysPermissionMapper.select(sysPermission);

        } else {
            topMenu = sysPermissionMapper.findPerByUser(MyShiroUtils.getSessionUserId(), 0);
        }
        if (CollectionUtil.isNotEmpty(topMenu)) {
            comparePermission(parentIdMap, topMenu);
        } else {
            topMenu = new ArrayList<>();
        }
        return topMenu;
    }

    private void comparePermission(Map<Integer, List<SysPermission>> parentIdMap
            , List<SysPermission> permissions) {
        if (CollectionUtil.isNotEmpty(permissions)) {
            permissions.forEach(permission -> {
                if (parentIdMap.containsKey(permission.getId())) {
                    permission.setList(parentIdMap.get(permission.getId()));
                    comparePermission(parentIdMap, parentIdMap.get(permission.getId()));
                }
            });
        }
    }

    private List<TreeNode> per2TreeNode(List<SysPermission> permissions) {
        List<TreeNode> treeNodes = new ArrayList<>();
        permissions.forEach(permission -> {
            TreeNode treeNode = new TreeNode(permission.getId(), permission.getPermissionName());
            treeNode = per2TreeNode(treeNode, permission);
            treeNodes.add(treeNode);
        });
        return treeNodes;
    }

    private TreeNode per2TreeNode(TreeNode treeNode, SysPermission permission) {
        if (permission.getList() != null && permission.getList().size() > 0) {
            List<TreeNode> treeNodes = new ArrayList<>();
            permission.getList().forEach(per -> {
                TreeNode node = new TreeNode(per.getId(), per.getPermissionName());
                if (per.getList() != null && per.getList().size() > 0) {
                    node = per2TreeNode(node, per);
                }
                treeNodes.add(node);
            });
            treeNode.setChildren(treeNodes);
        }
        return treeNode;
    }

    /**
     * @param userId 0表示获取所有目录，不为0获取指定用户的指定目录
     * @return
     */
    private List<SysPermission> getMenu(int userId) {
        List<SysPermission> permissionList = new ArrayList<>();
        if (userId == 0) {//admin
            permissionList = getSonMenu(0, null);
        } else {
            permissionList = sysPermissionMapper.findPerByUser(userId, 0);
            List<Integer> validIds = sysPermissionMapper.findPerIdsByUser(userId);
            if (permissionList == null) {
                return new ArrayList<>();
            }
            permissionList.forEach(permission -> {
                List<SysPermission> permissions = getSonMenu(permission.getId(), validIds);
                permission.setList(permissions);
            });
        }
        return permissionList;
    }

    private List<SysPermission> getSonMenu(int parentId, List<Integer> validIds) {
        List<SysPermission> permissions = sysPermissionMapper.findPerByFatherId(parentId, validIds);
        if (permissions != null) {
            permissions.forEach(permission -> {
                List<SysPermission> permissionList = getSonMenu(permission.getId(), validIds);
                if (permission != null) {
                    permission.setList(permissionList);
                }
            });
        }
        return permissions;
    }
}
